import 'package:dartkit/dartkit.dart';
import 'package:test/test.dart';

Future<User> createUser([String phone = phone]) async =>
    await userTable.create({"phone": phone});

void main() {
  prepareAndCleanPostgres("users_test_db");

  test("创建用户手机号格式检查", () {
    // 无参数报错
    expect(() async => await userTable.create({}), isBug);
    // 如果检查到手机号不符合格式，则创建会失败
    expect(() async => await userTable.create({"phone": ""}), isPostgresBug);
    expect(() async => await userTable.create({"phone": "214124"}),
        isPostgresBug); // 位数不全
    expect(() async => await userTable.create({"phone": "9876543210"}),
        isPostgresBug); // 没有以数字1开头
  });

  test("查找自动创建的用户", () async {
    // 由于在prepare中已经有创建用户的操作了，因此在这里直接检测就可以
    // 现在能够根据id找到用户
    final User? foundAfter = await userTable.find(idTest);
    expect(foundAfter, isNotNull);
  });

  test("寻找所有用户", () async {
    // 一开始只能找到默认的用户
    List<User> foundBefore = await userTable.findAll();
    expect(foundBefore, hasLength(1));
    // 创建多个用户
    await createUser("12345678901");
    await createUser("12345678902");
    await createUser("12345678903");
    // 查找所有用户，可以找到3个用户
    List<User> foundAfter = await userTable.findAll();
    expect(foundAfter, hasLength(4));
  });

  test("根据手机号查找测试", () async {
    // 根据手机号查找，能够找到默认创建的用户
    final User? foundAfter = await userTable.findByPhone(phone);
    expect(foundAfter, isNotNull);
  });

  test("更新用户测试", () async {
    // 创建一个用户后，它的初始值应该符合预期
    final User? user = await userTable.findByPhone(phone);
    expect(user, isNotNull);
    expect(user!.nick, "");
    expect(user.isAdmin, isFalse);
    expect(user.id, idTest);
    expect(user.phone, phone);
    expect(user.sms, null);

    // 修改用户的名字，和管理员权限和sms信息
    final sms = Sms.create(expireTime: Duration(minutes: 10));
    user.sms = sms;
    user.nick = "酸性量子";
    user.isAdmin = true;
    user.phone = "12345678900";
    await userTable.update(user);

    // 找到id相同的用户，发现名字已经更新
    final User? found = await userTable.find(idTest);
    expect(found?.nick, "酸性量子");
    expect(found?.isAdmin, isTrue);
    expect(found?.sms?.code, sms.code);
    expect(found?.phone, "12345678900");
  });

  test("错误更新手机号", () async {
    // 创建一个用户，并将手机更改为非法并保存，可以得到保存失败
    final User user = await userTable.findOrCreate(phone);
    user.phone = "645312";
    expect(() async => await userTable.update(user), isPostgresBug);
  });
}
